package com.zzzgroup;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class AppController {

	private static AppController _instance;
	private SharedPreferences _preferences;

	private PomodoroTime _time;
	private Timer _timer;

	public static AppController Instance() {
		if (_instance == null)
			_instance = new AppController();
		return _instance;
	}

	private AppController() {
		_time = new PomodoroTime(25 * 60, 5 * 60);

	}

	public void setPreferences(SharedPreferences value) {
		_preferences = value;
		if (!_preferences.contains("workTime")) {
			setSettingLong("workTime", _time.getWorkTime());
		}
		if (!_preferences.contains("restTime")) {
			setSettingLong("restTime", _time.getRestTime());
		}
	}

	public Timer getTimer() {
		return _timer;
	}

	public void setTimer(Timer timer) {
		_timer = timer;
	}

	public void setTime(long workTime, long restTime) {
		if (!((_time.getWorkTime() == workTime) && (_time.getRestTime() == restTime))) {
			setSettingLong("workTime", workTime);
			setSettingLong("restTime", restTime);
			_time = new PomodoroTime(workTime, restTime);

			if (_timer != null) {
				_timer.setTime(_time);
			}
		}
	}

	public PomodoroTime getTime() {
		return _time;
	}

	/*
	 * public long getWorkTime () throws KeyNotFoundInPreferencesException {
	 * return getSettingLong("workTime"); }
	 * 
	 * public long getRestTime () throws KeyNotFoundInPreferencesException {
	 * return getSettingLong("restTime"); }
	 */

	private void setSettingLong(String key, long value) {
		if (_preferences != null) {
			Editor editor = _preferences.edit();
			editor.putLong(key, value);
			editor.commit();
		}
	}

	private Long getSettingLong(String key)
			throws KeyNotFoundInPreferencesException {
		if ((_preferences != null) && (_preferences.contains(key))) {
			return _preferences.getLong(key, -1L);
		}
		throw new KeyNotFoundInPreferencesException();
	}
}
